<!--
 * @Author: liaoxing
 * @Date: 2022-03-21 14:07:20
 * @LastEditors: liaoxing
 * @LastEditTime: 2022-03-22 11:03:46
 * @Description: liaoxing created
 * @FilePath: \pin-xin-admin\src\views\system\account\index.vue
-->
<template>
  <div class="customerQuote">
    <header class="flex-align-center relative">
      <el-select style="width: 120px" v-model="keyCode" placeholder="请选择" size="mini">
        <el-option
          v-for="item in keyOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>

      <el-form :inline="true" :model="searchValue" class="demo-form-inline" size="mini">
        <el-form-item>
          <el-input v-model="searchValue.searchData"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchList">查询</el-button>
          <el-button @click="resetList">重置</el-button>
        </el-form-item>
      </el-form>
      <el-button type="primary" size="mini" class="absolute" style="right: 16px" @click="dialogFormVisible = true">新增账号</el-button>
    </header>
    <main>
      <el-table
        :header-cell-style="{backgroundColor: '#F2F6FC'}"
        :data="tableList"
        border
        style="width: 100%"
        v-loading="loading">

        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="100">
        </el-table-column>

        <el-table-column
          v-for="item in tableRenderList"
          align="center"
          :key="item.key"
          :prop="item.key"
          :label="item.label"
          :width="item.width || 'auto'">
        </el-table-column>

        <el-table-column
          label="账户状态"
          align="center"
          prop="status"
          width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status" type="success">启用</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="操作">
          <template slot-scope="scope">
            <div class="operateBox">
              <span class="color-blue" @click="openEditPassword(scope.row)"><i class="el-icon-edit-outline"></i>修改密码</span>
              <span class="color-blue" @click="resetPassword(scope.row.id)"><i class="el-icon-refresh-right"></i>重置密码</span>
              <span :class="scope.row.status ? 'color-red' : 'color-blue'" @click="forbiddenAccount(scope.row)"><i class="el-icon-setting"></i>{{ scope.row.status ? "禁用" : "启用" }}</span>
              <span class="color-red">
                <el-popconfirm
                  title="确定删除该账号吗？"
                  @confirm="deleteAccount(scope.row.id)"
                >
                  <span slot="reference"><i class="el-icon-delete"></i>删除</span>
                </el-popconfirm>
              </span>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="float: right; margin-top: 20px"
        :current-page.sync="searchValue.pn"
        :page-size="searchValue.ps"
        layout="total, prev, pager, next, jumper"
        :total="totalSize"
      ></el-pagination>
    </main>

    <el-dialog title="新增账号" :visible.sync="dialogFormVisible" width="30%">
      <el-form :model="addAccountForm" ref="accountForm" :rules="addAccountFormRule" label-width="100px">
        <el-form-item label="账号名称" prop="account">
          <el-input v-model="addAccountForm.account" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码" :rules="[{ required: true, validator: checkPassword, trigger: 'change' }]">
          <el-input v-model="addAccountForm.password" show-password autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="confirmPassword" label="确认密码" :rules="[{ required: true, validator: checkComfirmPassword, trigger: 'blur' }]">
          <el-input v-model="addAccountForm.confirmPassword" show-password autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="绑定用户" prop="userId">
          <el-input v-show="false" v-model="addAccountForm.userId" autocomplete="off"></el-input>
          <selectMember ref="selectMember" :selectMemberList.sync="selectMemberList" :showPhone="true" :showConfirm="false"  @getSelectMemberList="getSelectMemberList" :multiple="false"></selectMember>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmForm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改" :visible.sync="dialogFormVisiblePassword" width="30%">
      <el-form :model="passwordForm" ref="passwordForm" label-width="100px">
        <el-form-item prop="originPassword" label="旧密码" :rules="[{ required: true, validator: checkPassword, trigger: 'change' }]">
          <el-input v-model="passwordForm.originPassword" show-password autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码" :rules="[{ required: true, validator: checkPassword, trigger: 'change' }]">
          <el-input v-model="passwordForm.password" show-password autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="confirmPassword" label="确认密码" :rules="[{ required: true, validator: checkComfirmPassword2, trigger: 'blur' }]">
          <el-input v-model="passwordForm.confirmPassword" show-password autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisiblePassword = false">取 消</el-button>
        <el-button type="primary" @click="confirmPasswordForm">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import selectMember from '@/components/selectMember'
import account from '@/api/system/account'
import validatorAccount from '@/utils/jstar/checkAccount'
import validatorCheckPassword from '@/utils/jstar/checkPassword'
export default {
  name: "customerQuote",
  data () {
    let checkAccount = (rule, value, callback) => {
      if (!value) {
        callback(new Error('账号名称不能为空'))
        return
      }
      let flag = validatorAccount(value, 11, '账号')
      if (flag) {
        callback(new Error(flag))
        return
      }

      callback()
    }
    return {
      loading: false,
      keyOptions: [
        {label: "账号名称", value: "account_like"},
        {label: "用户名", value: "userName_like"},
      ],
      keyCode: 'account_like',
      searchValue: {
        searchData: '',
        pn: 1,
        ps: 10,
      },
      tableRenderList: [
        {label: "用户名", key: "userName", width: 200},
        {label: "账号名称", key: "account"},
        {label: "创建时间", key: "created"},
        // {label: "账户状态", key: "status"},
        // {label: "审核人", key: "key5"},
        // {label: "是否有报价", key: "key6"},
        // {label: "审核日期", key: "key7"}
      ],
      tableList: [],
      totalSize: 0,
      selectMemberList: [],

      dialogFormVisible: false,
      dialogFormVisiblePassword: false,
      addAccountForm: {
        account: '',
        password: '',
        confirmPassword: '',
        userId: '',
        userName: ''
      },
      passwordForm: {
        originPassword: "",
        password: "",
        id: "",
        confirmPassword: ''
      },

      addAccountFormRule: {
        account: [
          { required: true, validator: checkAccount, trigger: 'change' },
        ],
        // password: [
        //   { required: true, validator: checkPassword, trigger: 'blur' }
        // ],
        userId: [
          { required: true, message: '请选择用户', trigger: 'blur' },
        ]
      },
      checkPassword: null,
      checkComfirmPassword: null,
      checkComfirmPassword2: null 
    }
  },
  components: {selectMember},
  watch: {
    dialogFormVisible (value) {
      if (!value) {
        this.addAccountForm = {
          account: '',
          password: '',
          confirmPassword: '',
          userId: '',
          userName: ''
        }
        this.selectMemberList = []
        this.$refs.selectMember.clearSelect()
        this.$refs.accountForm.resetFields()
      }
    },
    dialogFormVisiblePassword (value) {
      if (!value) {
        this.passwordForm = {
          originPassword: "",
          password: "",
          id: "",
          confirmPassword: ''
        }
        this.$refs.passwordForm.resetFields()
      }
    },
    selectMemberList: {
      deep: true,
      handler (value) {
        if (value.length) {
          this.$refs.accountForm.fields[3].validateDisabled = true
          this.$refs.accountForm.fields[3].validateMessage = ''
          this.$refs.accountForm.fields[3].validateState = 'success'
        }
      }
    }
  },
  created () {
    this.queryAccountList()
    
    this.checkPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('密码不能为空'))
        return
      }
      let flag = validatorCheckPassword(value)
      if (flag) {
        callback(new Error(flag))
        return
      }
      callback()
    }

    this.checkComfirmPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('密码不能为空'))
        return
      }
      if (value != this.addAccountForm.password) {
        callback(new Error('两次密码不一致，请重新输入'))
        return
      }
      callback()
    }

    this.checkComfirmPassword2 = (rule, value, callback) => {
      if (!value) {
        callback(new Error('密码不能为空'))
        return
      }
      if (value != this.passwordForm.password) {
        callback(new Error('两次密码不一致，请重新输入'))
        return
      }
      callback()
    }
  },
  methods: {
    getSelectMemberList (list) {
      this.addAccountForm.userId = list[0].id
    },
    /* 查询 */
    searchList () {
      this.searchValue.pn = 1
      this.queryAccountList()
    },
    /* 重置 */
    resetList () {
      this.searchValue.pn = 1
      this.searchValue.searchData = ''
      this.queryAccountList()
    },
    /* 获取分页 */
    queryAccountList () {
      this.loading = true
      let params = JSON.parse(JSON.stringify(this.searchValue))
      if (params.searchData) {
        params[this.keyCode] = params.searchData
      }
      delete params.searchData
      account.queryAccount(params)
        .then(res => {
          this.loading = false
          if (res.code === 200) {
            this.tableList = res.data.rows
            this.totalSize = res.data.total * 1
          } else {
            this.$message.error(res.code + '-' + res.msg)
          }
        })
        .catch(e => {
          this.$message.error(e.toString())
        })
    },
    /* 确认提交 */
    confirmForm () {
      if (this.selectMemberList.length) {
        this.addAccountForm.userId = this.selectMemberList[0].id
        this.addAccountForm.userName = this.selectMemberList[0].name
      } else {
        this.addAccountForm.userId = ''
        this.addAccountForm.userName = ''
      }
      // this.dialogFormVisible = false
      this.$refs.accountForm.validate((valid) => {
        if (valid) {
          this.addAccount()
        } else {
          return false;
        }
      })
    },
    /* 添加账号 */
    addAccount () {
      let params = JSON.parse(JSON.stringify(this.addAccountForm))
      delete params.confirmPassword
      account.addAccount(params)
        .then(res => {
          if (res.code === 200) {
            this.$message.success("添加成功！")
            this.searchValue.pn = 1
            this.searchValue.searchData = ''
            this.queryAccountList()
            this.dialogFormVisible = false
          } else {
            this.$message.error(res.code + '-' + res.msg)
          }
        })
        .catch(e => {
          this.$message.error(e.toString())
        })
    },
    /* 打开密码修改 */
    openEditPassword (item) {
      this.passwordForm.id = item.id
      this.dialogFormVisiblePassword =true
    },
    /* 确认密码修改 */
    confirmPasswordForm () {
      this.$refs.passwordForm.validate((valid) => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this.passwordForm))
          delete params.confirmPassword
          account.changePassword(params.id, params)
            .then(res => {
              if (res.code === 200) {
                this.$message.success("修改成功！")
                this.dialogFormVisiblePassword = false
              } else {
                this.$message.error(res.code + '-' + res.msg)
              }
            })
            .catch(e => {
              this.$message.error(e.toString())
            })
        } else {
          return false;
        }
      })
    },
    /* 重置 */
    resetPassword (id) {
      account.resetPassword(id)
        .then(res => {
          if (res.code === 200) {
            this.$message.success("重置成功！")
          } else {
            this.$message.error(res.code + '-' + res.msg)
          }
        })
        .catch(e => {
          this.$message.error(e.toString())
        })
    },
    /* 删除 */
    deleteAccount (id) {
      account.deleteAccount(id)
        .then(res => {
          if (res.code === 200) {
            this.$message.success("删除成功！")
            this.queryAccountList()
          } else {
            this.$message.error(res.code + '-' + res.msg)
          }
        })
        .catch(e => {
          this.$message.error(e.toString())
        })
    },
    /* 修改状态 */
    forbiddenAccount (item) {
      account.editAccount(item.id, {status: item.status == 0 ? 1 : 0})
        .then(res => {
          if (res.code === 200) {
            this.$message.success("操作成功！")
            item.status = item.status == 0 ? 1 : 0
          } else {
            this.$message.error(res.code + '-' + res.msg)
          }
        })
        .catch(e => {
          this.$message.error(e.toString())
        })
    }
  }
}
</script>

<style lang="less">
.customerQuote{
  width: 100%;
  height: calc(100vh - 84px);
  box-sizing: border-box;
  padding: 16px;
  position: relative;
  background-color: #F3F5FA;
  header{
    height: 50px;
    padding: 0 16px;
    background-color: white;
    .el-form-item--mini.el-form-item{
      margin-bottom: 0;
      margin-left: 16px;
    }
  }
  main{
    margin-top: 16px;
    background-color: white;
    height: calc(100% - 66px);
    box-sizing: border-box;
    padding: 16px;
    .operateBox{
      &>span{
        margin: 0 8px;
        cursor: pointer;
      }
    }
  }
}
</style>